<template>
  <div>
    <div class="topSearch">
      <div>
        <el-select
          v-if="pageName === 'recharge'"
          v-model="searchCriteria.status"
          v-loading="loading"
          clearable
          placeholder="Status"
        >
          <el-option
            v-for="item in rechargeAuditStatus"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
        <el-input
          v-if="pageName === 'disputeAudit'"
          v-model="searchCriteria.productOrderNo"
          clearable
          placeholder="Order Number"
        />
        <el-input
          v-if="pageName === 'transaction'"
          v-model="searchCriteria.tradeNo"
          clearable
          placeholder="Trade Number"
        />
        <el-input
          v-if="pageName === 'transaction'"
          v-model="searchCriteria.productOrderPackageNo"
          clearable
          placeholder="PackageNumber"
        />
        <el-select
          v-if="pageName === 'disputeAudit'"
          v-model="searchCriteria.storeId"
          clearable
          placeholder="Store Name"
          @visible-change="getStoreAuthorList"
        >
          <el-option
            v-for="item in storeAuthorOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-if="pageName === 'disputeAudit'"
          v-model="searchCriteria.auditStatus"
          clearable
          placeholder="Audit Status"
        >
          <el-option
            v-for="item in disputeAuditStatus"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-if="pageName === 'transaction'"
          v-model="searchCriteria.tradeType"
          clearable
          placeholder="Trade Type"
        >
          <el-option
            v-for="item in transactionType"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-if="pageName === 'transaction'"
          v-model="searchCriteria.tradeStatus"
          clearable
          placeholder="Trade Status"
        >
          <el-option
            v-for="item in transactionStatus"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
        <el-date-picker
          v-model="searchDate"
          class="myDatePicker"
          type="daterange"
          range-separator="to"
          start-placeholder="Start Date"
          end-placeholder="End Date"
          value-format="yyyy-MM-dd"
          @change="dateSelected"
        />
        <el-button type="primary" @click="searchData()">Search</el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="tableData" style="width: 100%">
      <el-table-column
        v-for="item in titles"
        :key="item.value"
        :prop="item.value"
        :label="item.name"
      >
        <template slot-scope="scope">
          <span v-if="item.value === 'auditStatus'">{{
            scope.row.auditStatus === 0 || scope.row.auditStatus
              ? disputeAuditStatus[scope.row.auditStatus + 1].label
              : ''
          }}</span>
          <span v-if="item.value === 'tradeStatus'">{{
            scope.row.tradeStatus === 0 || scope.row.tradeStatus
              ? transactionStatus[scope.row.tradeStatus / 10].label
              : ''
          }}</span>
          <span v-if="item.value === 'tradeType'">{{
            scope.row.tradeType
              ? transactionType[scope.row.tradeType - 1].label
              : ''
          }}</span>
          <span v-if="item.value === 'payType'">{{
            scope.row.payType === 0 ? "onLine" : "offLine" }}</span>
          <span v-if="item.value === 'isCancel'">{{
            scope.row.isCancel === 0 || scope.row.isCancel
              ? isCancelStatus[scope.row.isCancel].label
              : ''
          }}</span>
          <span v-if="item.value === 'status'">{{
            scope.row.status === 0 ? 'Not Paid' : 'settle'
          }}</span>
          <span
            v-if="
              item.value !== 'auditStatus' &&
                item.value !== 'isCancel' &&
                item.value !== 'status' &&
                item.value !== 'tradeStatus' &&
                item.value !== 'tradeType' &&
                item.value !== 'payType'
            "
          >{{ scope.row[item.value] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="pageName === 'disputeAudit'"
        label="operation"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            :disabled="scope.row.auditStatus !== 0 || scope.row.isCancel === 1"
            @click="cancelAuditBtn(scope.row.id)"
          ><span v-if="scope.row.isCancel === 1">Cancelled </span><span v-if="scope.row.isCancel !== 1">Cancel</span></el-button>
        </template>
      </el-table-column>
      <el-table-column
        v-if="pageName === 'personel'"
        label="Operation"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            :disabled="scope.row.pendingPayments <= 0"
            @click="RechargeBtn(scope.row.id, scope.row.pendingPayments)"
          >Recharge</el-button>
          <el-button
            type="text"
            size="small"
            :disabled="scope.row.pendingPayments <= 0"
            @click="payBtn(scope.row.id)"
          >Pay</el-button>
          <el-button
            type="text"
            size="small"
            @click="downloadBill(scope.row.createTime)"
          >Download</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="tableData.length"
      id="btmPagination"
      :class="{ open: sidebar }"
      :current-page="currentPage"
      :page-sizes="[10, 30, 50, 100, 200]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <edit-dialog
      v-if="showDialog"
      :note="noteText"
      :edit="isEdit"
      :name="titleValue"
      @close="closeDialog"
    />
    <detial-dialog
      v-if="showDetialDialog"
      :data="singleData"
      @closedetial="closeDetialDialog"
    />
    <!--充值弹框 -->
    <recharge-dialog
      v-if="dialogVisible"
      :id="billId"
      :list-recharge="listRecharge"
      @close="closeDialog"
    />
  </div>
</template>

<script>
import EditDialog from './editDialog';
import DetialDialog from './detialDialog';
import RechargeDialog from './rechargeDialog';
import utils from '@/utils/getUrlUtils';
import {
  consumptionPage,
  rechargePage,
  disputePage,
  myAccountPage,
  transactionPage,
  disputeInject,
  downloadBill,
  billPayment
} from '@/api/finance';
import { postResult } from '@/utils/dataFormat';
import { storeAuthorList } from '@/api/common';
export default {
  components: {
    EditDialog,
    DetialDialog,
    RechargeDialog
  },
  props: {
    pageName: {
      type: String,
      required: true
    },
    balance: {
      type: Number,
      default: 0
    },
    titles: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      searchCriteria: {},
      searchDate: '',
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 15,
      disputeAuditStatus: [
        { label: 'All', id: '' },
        { label: 'Not approved', id: 0 },
        { label: 'Passed', id: 1 },
        { label: 'Refuse', id: 2 }
        // { label: '取消', id: 3 }
      ],
      rechargeAuditStatus: [
        { label: 'all', id: '' },
        { label: 'Not approved', id: 0 },
        { label: 'Passed', id: 1 },
        { label: 'Refuse', id: 2 }
      ],
      isCancelStatus: [
        { label: 'Not cancelled', id: 0 },
        { label: 'cancelled', id: 1 }
      ],
      transactionType: [
        { label: 'All', id: '' },
        // { label: 'Recharge', id: 1 },
        { label: 'Deduction', id: 2 },
        { label: 'Refund', id: 3 }
      ],
      transactionStatus: [
        { label: 'All', id: '' },
        { label: 'Auditing', id: 10 },
        { label: 'No Deduction', id: 20 },
        { label: 'Success', id: 30 },
        { label: 'Failed', id: 40 }
      ],
      rules: {
        auditNote: [
          {
            min: 1,
            max: 50,
            message: 'At least 5 to 50 characters',
            trigger: 'blur'
          }
        ]
      },
      tableData: [],
      storeAuthorOptions: [],
      showDialog: false,
      dialogVisible: false,
      showDetialDialog: false,
      noteText: '',
      singleData: '',
      value: '',
      isEdit: '0',
      titleValue: '',
      dateSearch: '',
      pamarsAudit: {},
      dialogForm: {},
      listRecharge: 0,
      billId: 0,
      peddingMoney: 0
    };
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar.opened;
    }
  },
  mounted() {
    this.init();
    this.getStoreAuthorList();
    if (utils.getUrlKey('paymentStatus') === 'success') {
      this.$message.success('recharge success');
      const path = this.$route.path;
      this.$router.push(path);
    } else if (utils.getUrlKey('paymentStatus') === 'cancel') {
      this.$message.warning('recharge cancel');
      const path = this.$route.path;
      this.$router.push(path);
    }
  },
  methods: {
    init() {
      this.loading = true;
      if (this.pageName === 'consume') {
        this.urlPage = consumptionPage;
      } else if (this.pageName === 'recharge') {
        this.urlPage = rechargePage;
        this.parmars = {
          beginCreateTime: this.searchDate ? this.searchDate[0] : '',
          endCreateTime: this.searchDate ? this.searchDate[1] : '',
          ...this.searchCriteria,
          pageSize: this.pageSize,
          pageNo: this.currentPage
        };
      } else if (this.pageName === 'disputeAudit') {
        this.urlPage = disputePage;
        this.parmars = {
          beginCreateTime: this.searchDate ? this.searchDate[0] : '',
          endCreateTime: this.searchDate ? this.searchDate[1] : '',
          ...this.searchCriteria,
          pageSize: this.pageSize,
          pageNo: this.currentPage
        };
      } else if (this.pageName === 'transaction') {
        this.urlPage = transactionPage;
        this.parmars = {
          beginCreateTime: this.searchDate ? this.searchDate[0] : '',
          endCreateTime: this.searchDate ? this.searchDate[1] : '',
          ...this.searchCriteria,
          pageSize: this.pageSize,
          pageNo: this.currentPage
        };
      } else if (this.pageName === 'personel') {
        this.urlPage = myAccountPage;
        this.parmars = {
          beginCreateTime: this.searchDate ? this.searchDate[0] : '',
          endCreateTime: this.searchDate ? this.searchDate[1] : '',
          pageSize: this.pageSize,
          pageNo: this.currentPage
        };
      }
      this.urlPage(this.parmars).then((res) => {
        if (res.code === 200) {
          this.tableData = res.data.data;
          if (this.pageName === 'disputeAudit' || this.pageName === 'transaction') {
            this.tableData.forEach((item) => {
              item.amount = item.amount / 100;
            });
          }
          if (this.pageName === 'recharge') {
            this.tableData.forEach((item) => {
              item.amount = item.amount / 100;
              item.balance = item.balance / 100;
            });
          }
          if (this.pageName === 'personel') {
            this.tableData.forEach((item) => {
              item.amountPaid = item.amountPaid / 100;
              item.totalAmount = item.totalAmount / 100;
              item.pendingPayments = item.pendingPayments / 100;
            });
          }
          if (
            this.pageName !== 'disputeAudit' &&
            this.pageName !== 'personel' &&
            this.pageName !== 'transaction' &&
            this.pageName !== 'recharge'
          ) {
            this.tableData.forEach((item) => {
              item.userFinancialFlow.amount =
                item.userFinancialFlow.amount / 100;
              item.userFinancialFlow.balance =
                item.userFinancialFlow.balance / 100;
            });
            this.cloneData = JSON.parse(JSON.stringify(res.data.data));
          }
          this.total = res.data.totalCount;
        }
        this.loading = false;
      });
    },
    cancelAuditBtn(id) {
      this.$confirm(
        'After this operation, you cannot change it. Do you want to continue?',
        'warring',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      )
        .then(() => {
          disputeInject(id).then((res) => {
            postResult(res, this.$message, this.init);
          });
        })
        .catch(() => {
          this.$message.info('cancel');
        });
    },
    payBtn(id, waitMoney) {
      if (waitMoney > this.balance) {
        this.$message.warning('Insufficient balance, please recharge first');
        return;
      }
      billPayment(id).then((res) => {
        postResult(res, this.$message, this.init);
      });
    },
    // submitAudit(formName) {
    //   this.pamarsAudit.auditNote = this.dialogAuditForm.auditNote;
    //   this.$refs[formName].validate((valid) => {
    //     if (valid) {
    //       disputeInject(this.pamarsAudit).then((res) => {
    //         if (res.code === 200) {
    //           if (this.$refs['ruleAuditForm']) {
    //             this.$refs['ruleAuditForm'].resetFields();
    //           }
    //           this.dialogInjectVisible = false;
    //           this.init();
    //         }
    //       });
    //     }
    //   });
    // },
    RechargeBtn(id, money) {
      this.billId = id;
      this.peddingMoney = (money - this.balance);
      this.listRecharge = 1;
      this.dialogVisible = true;
    },
    downloadByBlob(res, message) {
      // 下载blob数据
      if (JSON.stringify(res) !== '{}') {
        message.success('The file has been downloaded');
        const contentDisposition = res.headers['content-disposition'];
        if (
          contentDisposition.indexOf('fileName') >= 0 ||
          contentDisposition.indexOf('filename') >= 0
        ) {
          const filename =
            contentDisposition.split('fileName=')[1] ||
            contentDisposition.split('filename=')[1];
          const blob = new Blob([res.data]);
          const downloadElement = document.createElement('a');
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          downloadElement.href = href;
          downloadElement.download = filename; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        }
      } else {
        message.error('An error occurred while downloading. No infomation available!!');
      }
    },
    downloadBill(time) {
      downloadBill({ createTime: time.substring(0, 10) }).then((res) => {
        if (res && res.status === 200) {
          this.downloadByBlob(res, this.$message);
        }
      });
    },
    dateSelected(selectVal) {
      // 选择日期后更新数据
      this.dateSearch = selectVal;
      this.init();
    },
    getStoreAuthorList(val) {
      if (!val) {
        return;
      }
      storeAuthorList({ storeType: 'VIRTUAL' }).then((res) => {
        this.storeAuthorOptions = res.data;
      });
    },
    searchData() {
      this.init();
    },
    lookBtn(data) {
      this.singleData = data;
      this.showDetialDialog = true;
    },
    edit(msg) {
      this.isEdit = '1';
      this.noteText = msg;
      this.titleValue = '编辑';
      this.showDialog = true;
    },
    rechargeBtn() {
      this.isEdit = '0';
      this.titleValue = '充值';
      this.showDialog = true;
    },
    closeDialog() {
      this.showDialog = false;
      this.dialogVisible = false;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    closeDetialDialog() {
      this.showDetialDialog = false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.init();
    }
  }
};
</script>
<style lang="scss" scoped>
.top-btn {
  margin: 10px 0;
}
.product-title {
  max-height: 50px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-height: 18px;
  -webkit-box-orient: vertical;
}
</style>
